//
// Created by seeed on 25-8-14.
//
//LED灯函数
#include "led.h"
#include <Arduino.h>

// Led类构造函数
Led::Led(uint8_t led_Pin, LED_Mode mode) : led_pin(led_Pin), mode(mode) {
    // 初始化引脚
    pinMode(led_pin, OUTPUT);
    digitalWrite(led_pin, LOW);
}

// 关闭LED灯
void Led::off() const {
    digitalWrite(led_pin, LOW);
}

// 打开LED灯
void Led::on() const {
    digitalWrite(led_pin, HIGH);
}

// 翻转LED灯状态
void Led::toggle() const {
    digitalWrite(led_pin, !digitalRead(led_pin));
}

// 设置LED亮度（0-255）
void Led::setBrightness(uint8_t brightness) const {
    if (mode == LED_MODE_PWM) {
        // 使用analogWrite实现PWM（如果平台支持）
        #if defined(ESP32) || defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAM)
            // 支持analogWrite的平台
            analogWrite(led_pin, brightness);
        #else
            // 其他平台使用软件PWM模拟
            if (brightness == 0) {
                digitalWrite(led_pin, LOW);
            } else if (brightness >= 255) {
                digitalWrite(led_pin, HIGH);
            } else {
                // 简单的软件PWM模拟
                digitalWrite(led_pin, brightness > 127 ? HIGH : LOW);
            }
        #endif
    } else {
        // 数字模式，根据亮度值决定开关
        digitalWrite(led_pin, brightness > 0 ? HIGH : LOW);
    }
}

// LED呼吸灯效果
void Led::breathe() const {
    if (mode == LED_MODE_PWM) {
        // 实现呼吸灯效果
        // 逐渐增加亮度
        for (int brightness = 5; brightness <= 255; brightness += 5) {
            setBrightness(brightness);
            delay(20);
        }
        // 逐渐减少亮度
        for (int brightness = 255; brightness >= 5; brightness -= 5) {
            setBrightness(brightness);
            delay(20);
        }
        // 确保完全关闭
        setBrightness(0);
    } else {
        // 数字模式下，使用简单的开关效果模拟呼吸灯
        on();
        delay(1000);
        off();
        delay(1000);
    }
}
